class Admin::ItemCategoriesController < AdminController
  before_filter :find_item_category, :only => [:children, :update, :destroy]
  
  def index
    @item_categories = ItemCategory.cat1.to_json
  end

  def create
    @item_category = ItemCategory.new({:name => params[:name],
      :sort_order => params[:sort_order],
      :parent_id => params[:parent_id],
      :cat_level => params[:cat_level]})

    if @item_category.save
      respond_to do |format|
        format.json { render :text => @item_category.to_json }
      end
    else
      respond_to do |format|
        format.json { render :text => {} }
      end
    end
  end
  
  def update
    if request.xhr?
      if @item_category.update_attribute(:name,params[:value])
        respond_to do |format|
          format.json { render :text => { :status => 'ok', :name => @item_category.name }.to_json }
        end
      else
        respond_to do |format|
          format.json { render :text => { :status => 'fail'}.to_json }
        end
      end
    end
  end
  
  def destroy
    @item_category.del
    flash[:notice] = "Successfully destroyed item category."
    
    respond_to do |format|
      format.html { redirect_to item_categories_url }
      format.json { render :text => {:status => 'ok'}.to_json }
    end
  end

  def sort
    data = params[:item_categories]
    #@category_count = data.size
    data.each do |d|
      ItemCategory.find(d[:id]).update_attribute('sort_order',d[:new_pos])
    end
    respond_to do |format|
      format.json { render :text => {:status => 'ok'}.to_json }
    end
  end

  def children
    respond_to do |format|
      format.json { render :text => @item_category.children.to_json }
    end
  end
  
  private
  
  def find_item_category
    @item_category = ItemCategory.find(params[:id])
  end
end
